<template>
  <div class="user-manage">
    <div class="page-header">
      <h2>用户管理</h2>
      <p>管理系统中的所有用户，包括启用、禁用、删除和角色分配</p>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <input 
        v-model="searchKeyword" 
        type="text" 
        placeholder="搜索用户名、手机号、邮箱..." 
        @input="handleSearch"
      />
    </div>

    <!-- 用户列表 -->
    <div class="user-table">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>学号</th>
            <th>手机号</th>
            <th>邮箱</th>
            <th>角色</th>
            <th>状态</th>
            <th>违规次数</th>
            <th>注册时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in filteredUsers" :key="user.id">
            <td>{{ user.id }}</td>
            <td>{{ user.username }}</td>
            <td>{{ user.studentNo || '-' }}</td>
            <td>{{ user.phone }}</td>
            <td>{{ user.email }}</td>
            <td>
              <div class="role-badges">
                <span 
                  v-for="(roleName, index) in (user.roleNames || [])" 
                  :key="index"
                  class="role-badge" 
                  :class="getRoleBadgeClass(user.roleCodes[index])"
                >
                  {{ roleName }}
                </span>
                <span v-if="!user.roleNames || user.roleNames.length === 0" class="role-badge role-none">
                  无角色
                </span>
              </div>
            </td>
            <td>
              <span class="status-badge" :class="user.status === 1 ? 'status-active' : 'status-disabled'">
                {{ user.status === 1 ? '正常' : '禁用' }}
              </span>
            </td>
            <td>
              <span :class="{ 'text-danger': user.violationCount > 0 }">
                {{ user.violationCount }}
              </span>
            </td>
            <td>{{ formatDate(user.createTime) }}</td>
            <td class="action-buttons">
              <button 
                v-if="user.status === 0" 
                @click="enableUser(user)" 
                class="btn-enable"
              >
                启用
              </button>
              <button 
                v-if="user.status === 1 && !isSuperAdmin(user)" 
                @click="disableUser(user)" 
                class="btn-disable"
              >
                禁用
              </button>
              <button @click="openRoleDialog(user)" class="btn-role">角色</button>
              <button 
                v-if="!isSuperAdmin(user)" 
                @click="deleteUser(user)" 
                class="btn-delete"
              >
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 角色分配对话框 -->
    <div v-if="showRoleDialog" class="modal-overlay" @click.self="closeRoleDialog">
      <div class="modal-content">
        <div class="modal-header">
          <h3>为 {{ currentUser.username }} 分配角色</h3>
          <button @click="closeRoleDialog" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <div class="current-roles">
            <h4>当前角色：</h4>
            <div class="role-tags">
              <span 
                v-for="role in userRoles" 
                :key="role.id" 
                class="role-tag"
              >
                {{ role.roleName }}
                <!-- 超级管理员角色不显示移除按钮 -->
                <button 
                  v-if="role.roleCode !== 'SUPER_ADMIN'" 
                  @click="removeRole(role)" 
                  class="remove-role"
                >&times;</button>
                <span v-else class="lock-icon" title="系统保护角色，不可移除">🔒</span>
              </span>
              <span v-if="userRoles.length === 0" class="no-data">未分配角色</span>
            </div>
          </div>
          <div class="assign-roles">
            <h4>分配新角色：</h4>
            <div class="role-list">
              <label 
                v-for="role in availableRoles" 
                :key="role.id" 
                class="role-checkbox"
              >
                <input 
                  type="checkbox" 
                  :value="role.id" 
                  v-model="selectedRoles"
                />
                <span>{{ role.roleName }} ({{ role.roleCode }})</span>
              </label>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="assignRoles" class="btn-primary">确定分配</button>
          <button @click="closeRoleDialog" class="btn-cancel">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as adminAPI from '@/api/admin'

const users = ref([])
const roles = ref([])
const searchKeyword = ref('')
const showRoleDialog = ref(false)
const currentUser = ref(null)
const userRoles = ref([])
const selectedRoles = ref([])

// 过滤后的用户列表
const filteredUsers = computed(() => {
  if (!searchKeyword.value) return users.value
  const keyword = searchKeyword.value.toLowerCase()
  return users.value.filter(user => 
    user.username?.toLowerCase().includes(keyword) ||
    user.phone?.includes(keyword) ||
    user.email?.toLowerCase().includes(keyword) ||
    user.studentNo?.includes(keyword)
  )
})

// 可分配的角色（排除已有的，且不包括超级管理员角色）
const availableRoles = computed(() => {
  const userRoleIds = userRoles.value.map(r => r.id)
  return roles.value.filter(r => 
    !userRoleIds.includes(r.id) && 
    r.roleCode !== 'SUPER_ADMIN'  // 不允许分配超级管理员角色
  )
})

// 获取所有用户
const loadUsers = async () => {
  try {
    const res = await adminAPI.getAllUsers()
    if (res.code === 200) {
      users.value = res.data || []
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}

// 获取所有角色
const loadRoles = async () => {
  try {
    const res = await adminAPI.getAllRoles()
    if (res.code === 200) {
      roles.value = res.data || []
    }
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  }
}

// 启用用户
const enableUser = async (user) => {
  try {
    const res = await adminAPI.enableUser(user.id)
    if (res.code === 200) {
      ElMessage.success('启用用户成功')
      loadUsers()
    } else {
      ElMessage.error(res.msg || '启用用户失败')
    }
  } catch (error) {
    ElMessage.error('启用用户失败')
  }
}

// 禁用用户
const disableUser = async (user) => {
  try {
    await ElMessageBox.confirm(`确定要禁用用户 ${user.username} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await adminAPI.disableUser(user.id)
    if (res.code === 200) {
      ElMessage.success('禁用用户成功')
      loadUsers()
    } else {
      ElMessage.error(res.msg || '禁用用户失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('禁用用户失败')
    }
  }
}

// 删除用户
const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${user.username} 吗？此操作不可恢复！`, 
      '警告', 
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    const res = await adminAPI.deleteUser(user.id)
    if (res.code === 200) {
      ElMessage.success('删除用户成功')
      loadUsers()
    } else {
      ElMessage.error(res.msg || '删除用户失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除用户失败')
    }
  }
}

// 打开角色分配对话框
const openRoleDialog = async (user) => {
  currentUser.value = user
  selectedRoles.value = []
  try {
    const res = await adminAPI.getUserRoles(user.id)
    if (res.code === 200) {
      userRoles.value = res.data || []
      showRoleDialog.value = true
    }
  } catch (error) {
    ElMessage.error('获取用户角色失败')
  }
}

// 关闭角色对话框
const closeRoleDialog = () => {
  showRoleDialog.value = false
  currentUser.value = null
  userRoles.value = []
  selectedRoles.value = []
}

// 移除角色
const removeRole = async (role) => {
  try {
    await ElMessageBox.confirm(`确定要移除 ${role.roleName} 角色吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await adminAPI.removeUserRole({
      userId: currentUser.value.id,
      roleId: role.id
    })
    
    if (res.code === 200) {
      ElMessage.success('移除角色成功')
      openRoleDialog(currentUser.value)
    } else {
      ElMessage.error(res.msg || '移除角色失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('移除角色失败')
    }
  }
}

// 分配角色
const assignRoles = async () => {
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请选择要分配的角色')
    return
  }
  
  try {
    for (const roleId of selectedRoles.value) {
      await adminAPI.assignRoleToUser({
        userId: currentUser.value.id,
        roleId: roleId
      })
    }
    ElMessage.success('分配角色成功')
    closeRoleDialog()
    loadUsers()
  } catch (error) {
    ElMessage.error('分配角色失败')
  }
}

// 判断是否为超级管理员
const isSuperAdmin = (user) => {
  // 基于 RBAC 角色判断
  const roleCodes = user.roleCodes || []
  return roleCodes.includes('SUPER_ADMIN')
}

// 获取角色文本（旧方法，保留兼容性）
const getRoleText = (role) => {
  const roleMap = {
    0: '普通用户',
    1: '管理员',
    2: '超级管理员'
  }
  return roleMap[role] || '未知'
}

// 根据角色代码获取角色标签样式
const getRoleBadgeClass = (roleCode) => {
  const roleClassMap = {
    'SUPER_ADMIN': 'role-super-admin',
    'ADMIN': 'role-admin',
    'USER': 'role-user'
  }
  return roleClassMap[roleCode] || 'role-default'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

// 搜索处理
const handleSearch = () => {
  // 实时过滤，computed已处理
}

// 组件挂载时加载数据
onMounted(() => {
  loadUsers()
  loadRoles()
})
</script>

<style scoped>
.user-manage {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header h2 {
  margin: 0 0 10px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-bar {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-bar input {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-bar input:focus {
  outline: none;
  border-color: #42b983;
}

.user-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

table {
  width: 100%;
  border-collapse: collapse;
}

thead {
  background: #f8f8f8;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

th {
  font-weight: 600;
  color: #333;
}

td {
  color: #666;
}

.role-badges {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.role-badge, .status-badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

/* 旧的角色样式（兼容） */
.role-0 {
  background: #e3f2fd;
  color: #1976d2;
}

.role-1 {
  background: #fff3e0;
  color: #f57c00;
}

.role-2 {
  background: #f3e5f5;
  color: #7b1fa2;
}

/* 新的 RBAC 角色样式 */
.role-super-admin {
  background: #f3e5f5;
  color: #7b1fa2;
  border: 1px solid #ce93d8;
}

.role-admin {
  background: #fff3e0;
  color: #f57c00;
  border: 1px solid #ffb74d;
}

.role-user {
  background: #e3f2fd;
  color: #1976d2;
  border: 1px solid #64b5f6;
}

.role-none {
  background: #f5f5f5;
  color: #999;
  border: 1px solid #ddd;
}

.role-default {
  background: #e0e0e0;
  color: #666;
  border: 1px solid #bdbdbd;
}

.status-active {
  background: #e8f5e9;
  color: #2e7d32;
}

.status-disabled {
  background: #ffebee;
  color: #c62828;
}

.text-danger {
  color: #f44336;
  font-weight: 600;
}

.action-buttons {
  white-space: nowrap;
}

.action-buttons button {
  padding: 6px 12px;
  margin-right: 5px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
}

.btn-enable {
  background: #4caf50;
  color: white;
}

.btn-enable:hover {
  background: #45a049;
}

.btn-disable {
  background: #ff9800;
  color: white;
}

.btn-disable:hover {
  background: #fb8c00;
}

.btn-role {
  background: #2196f3;
  color: white;
}

.btn-role:hover {
  background: #1e88e5;
}

.btn-delete {
  background: #f44336;
  color: white;
}

.btn-delete:hover {
  background: #e53935;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow: auto;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 28px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  line-height: 1;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.current-roles, .assign-roles {
  margin-bottom: 20px;
}

.current-roles h4, .assign-roles h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 14px;
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.role-tag {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 6px 12px;
  background: #42b983;
  color: white;
  border-radius: 16px;
  font-size: 13px;
}

.remove-role {
  background: rgba(255,255,255,0.3);
  border: none;
  color: white;
  cursor: pointer;
  padding: 0;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  font-size: 14px;
  line-height: 1;
}

.remove-role:hover {
  background: rgba(255,255,255,0.5);
}

.lock-icon {
  margin-left: 8px;
  font-size: 14px;
  opacity: 0.8;
  cursor: help;
}

.no-data {
  color: #999;
  font-size: 13px;
}

.role-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.role-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.role-checkbox:hover {
  background: #f5f5f5;
  border-color: #42b983;
}

.role-checkbox input[type="checkbox"] {
  cursor: pointer;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn-primary {
  padding: 8px 20px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-primary:hover {
  background: #3aa876;
}

.btn-cancel {
  padding: 8px 20px;
  background: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-cancel:hover {
  background: #e0e0e0;
}
</style>

